package com.itheima.health.task;

import com.itheima.health.dao.ReportDao;
import com.itheima.health.service.impl.ReportServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 李宜之创建于2024.4.16
 *
 */
@Component
@Slf4j
public class ReportTask {
    @Autowired
    ReportDao reportDao;



    //本方法用于每月一号，刷新ReportServiceimpl.memberReport静态变量的值
    @Scheduled(cron = "1 0 0 1 * *")
    public void setmemberReporttask(){
        LocalDate startday = LocalDate.now().minusYears(1);
        List<LocalDate> monthStartdays = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            monthStartdays.add(LocalDate.now().minusMonths(12 - i).withDayOfMonth(1));
        }

        List<String> months = new ArrayList<>();
        List<Integer> memberCount = new ArrayList<>();
        //查找数据库，填充月份和会员总数
        monthStartdays.forEach(localDate -> {
            months.add(localDate.format(DateTimeFormatter.ofPattern("yyyy.MM")));
            memberCount.add(reportDao.selectmemberCount(localDate, localDate.withDayOfMonth(localDate.lengthOfMonth())));
        });
        ReportServiceImpl.memberReport.setMonths(months);
        ReportServiceImpl.memberReport.setMemberCount(memberCount);

    }
}
